package cn.dida.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.dida.exception.BizzException;
import cn.dida.model.Activity;
import cn.dida.model.ActivityPrize;
import cn.dida.model.ActivityRegion;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.Pageable;
import cn.dida.model.Product;
import cn.dida.model.UserSession;
import cn.dida.service.ActivityService;
import cn.dida.service.ProductService;
import cn.dida.util.DateUtils;
import cn.dida.util.ExcelUtil;

/**
 * <p>活动管理</p>
 * @author lisha
 * @date 2016-11-14 14:36
 * */
@Controller
public class ActivityController extends BaseController {
	
	@Autowired
	private ActivityService activityService;
	
	@Autowired
    private ProductService productService;
	
	/**
	 * 查看活动详情
	 * @param activityId 活动id
	 * @return ModelAndView
	 * */
	@GetMapping("/activity/getActivityDetail")
    public ModelAndView getActivityDetail(HttpServletRequest request, String activityId) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
       
		//详情页
		
		Activity activity = activityService.getActivityById(activityId);
		model.put("activity", activity);
		
		List<Product> selectedProductList = productService.getProductsByActivityId(activityId);
	    model.put("selectedProductList", selectedProductList);
	    
	    /*ActivityPrize aPrize = activityService.getActivityPrizeById(activityId);
	    model.put("aPrize", aPrize);*/
	    
	    model.put("selectedRgn", activityService.getRgnByActivityId(activityId));
	    
	    
		return new ModelAndView("activity_edit_detail").addAllObjects(model);
        
    }
	/**
	 * 查看活动中奖详情
	 * @param activityId 活动id
	 * @param page 分页游标
	 * @return ModelAndView
	 * */
	@GetMapping("/activity/getActivityPrizeDetail")
	public ModelAndView getActivityPrizeDetail(HttpServletRequest request, String activityId,Integer page) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		
		//详情页
        
        page = (page == null || page < 1) ? 1 : page;
        Pageable<ActivityPrize> result = activityService.queryActivityPrize(page,activityId);
        
        model.put("activityPrizeList", result);
        model.put("activityId", activityId);//活动id
		return new ModelAndView("activity_prize_detail").addAllObjects(model);
		
	}
	/**
	 * 获取活动简介详情
	 * @param activityId 活动id
	 * @return ModelAndView
	 * */
	@GetMapping("/activity/getActivityAbstractDetail")
    public ModelAndView getActivityAbstractDetail(HttpServletRequest request, String activityId) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        Activity activity = activityService.getActivityById(activityId);
        model.put("activityId", activityId);
        model.put("activity", activity);
        return new ModelAndView("activity_abstract_detail").addAllObjects(model);
	}
    
    /**
     * 已选择的商品
     * @param ids 已选择的商品id
     * @param keyword 查询条件
     * @param page 分页游标
	 * @return ModelAndView
     * */
    @GetMapping("/activity/selected")
    public ModelAndView selectedProduct(HttpServletRequest request, String ids, String keyword, Integer page) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        
        //去掉ids最后一位标点符
        //ids = ids.substring(0, ids.length()-1);
        
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
       // Pageable<Product> selectedProductList = productService.queryProduct(userSession.getCompanyId(), keyword, 1, page);
        Pageable<Product> selectedProductList = activityService.querySelected(userSession.getCompanyId(), keyword, 1, page);
        
        model.put("product1", selectedProductList);
        return new ModelAndView("activity_list").addAllObjects(model);
    }

    /**
     * 选择商品 关键字查询
     * @param keyword 查询条件
     * @param page 分页游标
     * @return HttpResponseBodyWrapper
     * */
    @PostMapping("/activity/getProductList")
    @ResponseBody
    public HttpResponseBodyWrapper getProductList(HttpServletRequest request, String keyword, Integer page) throws Exception {

        //去掉ids最后一位标点符
        //ids = ids.substring(0, ids.length()-1);

        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        //Pageable<Product> selectedProductList = productService.queryProduct(userSession.getCompanyId(), keyword, 1, page);
        Pageable<Product> selectedProductList = activityService.querySelected(userSession.getCompanyId(), keyword, 1, page);

        return new HttpResponseBodyWrapper(selectedProductList);
    }
	
	/**
	 * 活动列表
	 * @param name 活动名称
	 * @param sta 活动状态,0不可用，1正常使用,2手动停用
	 * @param cAdmin 创建人
	 * @param channel 渠道
	 * @param add 操作标记
	 * @param activityId 活动id
	 * @param page 分页游标
	 * @return ModelAndView
	 * */
	@GetMapping("/activity")
    public ModelAndView list(HttpServletRequest request, String name, Integer sta, String cAdmin,String channel, String add, String activityId,Integer page,HttpSession session) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        name = StringUtils.trimToEmpty(name);
        channel = StringUtils.trimToEmpty(channel);
        
        Pageable<Activity> activityList = activityService.queryActivity(userSession.getCompanyId(),name, cAdmin, sta, channel, page);
        if(activityList.getResultTotal() > 0){
        	for(int i = 0; i < activityList.getResult().size(); i++){
        		String selectedRgn = activityService.getRgnByActivityId(activityList.getResult().get(i).getId().toString());
        		activityList.getResult().get(i).setAreaName(selectedRgn);
        	}
        }
        
        model.put("activityList", activityList);
        model.put("name", name);
        model.put("channel", channel);
        model.put("sta", sta);
        
        //查询状态为使用中的商品,商品状态：1使用中，2已封存
        //Pageable<Product> productList = productService.queryProduct(userSession.getCompanyId(), "", 1, 1);
        Pageable<Product> productList = activityService.querySelected(userSession.getCompanyId(), "", 1, 1);
        model.put("productList1", productList);
        
        
        if(StringUtils.isNotBlank(add)){
        	return new ModelAndView("activity_new").addAllObjects(model);
        }else if(StringUtils.isNotBlank(activityId)){
        	//编辑页
        	
    		Activity activity = activityService.getActivityById(activityId);
    		model.put("activity", activity);
    		
    		List<Product> selectedProductList = productService.getProductsByActivityId(activityId);
            model.put("selectedProductList", selectedProductList);
            //标记编辑页面是否有活动商品关联数据
            if(selectedProductList.size() > 0){
            	model.put("prosFlag", 1);//表示有活动商品关联记录
            }else{
            	model.put("prosFlag", 0);//表示无活动商品关联记录
            }
            
            /*ActivityPrize aPrize = activityService.getActivityPrizeById(activityId);
            model.put("aPrize", aPrize);*/
            
            //model.put("selectedRgn", activityService.getRgnByActivityId(activityId));
            //标记编辑页面是否有活动区域关联数据
            List<ActivityRegion> selectedRgnList = activityService.getRgnById(activityId);
            if(selectedRgnList.size() > 0){
            	model.put("regFlag", 1);//表示有活动区域关联记录
            }else{
            	model.put("regFlag", 0);//表示无活动区域关联记录
            }
            model.put("selectedRgnList", activityService.getRgnById(activityId));
            
    		return new ModelAndView("activity_edit").addAllObjects(model);
        }else{
        	
        	return new ModelAndView("activity_list").addAllObjects(model);
        }
    }
	/**
	 * 活动列表导出
	 * @param name 活动名称
	 * @param sta 活动状态,0不可用，1正常使用,2手动停用
	 * @param channel 渠道
	 * @return ModelAndView
	 * */
	@GetMapping("/activity/export")
	public ModelAndView activity_export(HttpServletRequest request, HttpServletResponse response, String name, Integer sta, String channel) throws Exception {
		UserSession userSession = getUserSession(request);
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	if(StringUtils.isNotBlank(name)){
    		//活动名称
    		paramMap.put("name", name);
    	}
    	if(sta != null){
    		//活动状态：1正常，0未启用，2手动停用
    		paramMap.put("sta", sta);
    	}
    	if(StringUtils.isNotBlank(channel)){
    		//渠道
    		paramMap.put("channel", channel);
    	}
    	
		List<Activity> exportList = activityService.queryActivityForExport(userSession.getCompanyId(), name, sta, channel);
		if(exportList.size() > 0){
        	for(int i = 0; i < exportList.size(); i++){
        		String selectedRgn = activityService.getRgnByActivityId(exportList.get(i).getId().toString());
        		exportList.get(i).setAreaName(selectedRgn);
        	}
        }
		
    	String fileName="活动数据导出"+DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");
    	
    	List<Map<String,Object>> list= new ArrayList<Map<String,Object>>(exportList.size());
    	
    	Map<String,Object> fmap = null;
    	for(Activity obj : exportList){
    		fmap=new HashMap<String, Object>();
    		Long tid = NumberUtils.toLong(obj.getId().toString(), 0L);
    		fmap.put("id", tid);
    		fmap.put("name", obj.getName());
    		String time = DateUtils.transferLongToDate("yyyy-MM-dd", obj.getActTimeStart())+"至"+
    					DateUtils.transferLongToDate("yyyy-MM-dd", obj.getActTimeEnd());
    		fmap.put("time", time);
    		
    		fmap.put("area", obj.getAreaName());
    		fmap.put("channel", obj.getChannel());
    		
    		if(obj.getIsAutoDraw() == null){
    			fmap.put("isAutoDraw", "");
    		}else{
    			if(obj.getIsAutoDraw() == 0){
        			fmap.put("isAutoDraw", "否");
        		}else if(obj.getIsAutoDraw() == 1){
        			fmap.put("isAutoDraw", "是");
        		}
    		}
    		
    		
    		if(obj.getSta() == 0){
    			fmap.put("state", "未启用");
    			fmap.put("currentState", "活动未启用");
    		}else if(obj.getSta() == 1){
    			fmap.put("state", "启用");
    			
    			if(DateUtils.getcurrentTimeLong() < obj.getActTimeStart()){
    				fmap.put("currentState", "活动未开始");
    			}else if(DateUtils.getcurrentTimeLong() > obj.getActTimeEnd()){
    				fmap.put("currentState", "活动已结束");
    			}else{
    				fmap.put("currentState", "活动进行中");
    			}
    		}else if(obj.getSta() == 2){
	    		fmap.put("state", "已停用");
	    		fmap.put("currentState", "活动已停用");
	    	}
    		
    		fmap.put("cTime", DateUtils.formatTimeInMillis(obj.getcTime()));
    		fmap.put("cAdmin", obj.getcAdmin());
    		
    		list.add(fmap);
    	}
    	
    	String columnNames[] = {"ID","活动名称","活动时间","活动区域","渠道","自动抽奖","活动状态","当前状态","创建时间","创建人"};//列名
    	String keys[] = {"id","name","time","area","channel","isAutoDraw","state","currentState","cTime","cAdmin"};//map中的key
    	ByteArrayOutputStream os = new ByteArrayOutputStream();
    	try {
    		ExcelUtil.createWorkBook(list,keys,columnNames).write(os);
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    	byte[] content = os.toByteArray();
    	InputStream is = new ByteArrayInputStream(content);
    	// 设置response参数，可以打开下载页面
    	response.reset();
    	response.setContentType("application/vnd.ms-excel;charset=utf-8");
    	response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
    	ServletOutputStream out = response.getOutputStream();
    	BufferedInputStream bis = null;
    	BufferedOutputStream bos = null;
    	try {
    		bis = new BufferedInputStream(is);
    		bos = new BufferedOutputStream(out);
    		byte[] buff = new byte[2048];
    		int bytesRead;
    		// Simple read/write loop.
    		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    			bos.write(buff, 0, bytesRead);
    			bos.flush();
    		}
    	} catch (final IOException e) {
    		throw e;
    	} finally {
    		if (bis != null)
    			bis.close();
    		if (bos != null)
    			bos.close();
    	}
    	
    	return null;
	}
	
	/**
	 * 增加活动 
	 * @param activity 活动实体
	 * @return HttpResponseBodyWrapper
	 * */
	@ResponseBody
    @PostMapping("/activity")
    public HttpResponseBodyWrapper add(HttpServletRequest request, @RequestBody Activity activity) throws Exception {
        
        UserSession userSession = getUserSession(request);

        activity.setName(StringUtils.trimToNull(activity.getName()));
        activity.setcAdmin(userSession.getAccount());
        activity.setuAdmin(userSession.getAccount());
        activity.setCompanyId(userSession.getCompanyId());
        
        if (activity.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入活动名称");
        }
        /*if (StringUtils.isNotBlank(activity.getChannel())) {
        	activity.setChannel(activity.getChannel().substring(0, activity.getChannel().length()-1));
        }else{
        	throw new BizzException(BizzException.error_code_invalid_params, "请选择渠道");
        }*/
        if (activity.getChannel() == null) {
        	throw new BizzException(BizzException.error_code_invalid_params, "请选择渠道");
        }
        if(!StringUtils.isNotBlank(activity.getSelectedPros())){
        	throw new BizzException(BizzException.error_code_invalid_params, "请选择活动商品");
        }
        
        if(activity.getActBaseNub() == null){
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入参奖基数");
        }
        
        Boolean flag = activityService.isExistsActivity(String.valueOf(userSession.getCompanyId()), activity.getName());
        if(flag){
        	throw new BizzException(BizzException.error_code_invalid_params, "已存在名称为【"+activity.getName()+"】的活动");
        }
        int result = activityService.insertActivity(activity);
        return new HttpResponseBodyWrapper(result);
    }
	
	/**
	 * 删除活动
	 * @param id 活动id
	 * @return HttpResponseBodyWrapper
	 * */
	@ResponseBody
    @DeleteMapping("/activity/{id}")
    public HttpResponseBodyWrapper deleteBrand(HttpServletRequest request, @PathVariable int id) throws Exception {
		UserSession userSession = getUserSession(request);
        Boolean result = activityService.deleteActivity(userSession.getCompanyId(),id);
        return new HttpResponseBodyWrapper(result);
    }
	/**
	 * 删除活动与商品关联
	 * */
	/*@ResponseBody
    @DeleteMapping("/activity/delPro/{productId}")
    public HttpResponseBodyWrapper deletePro(HttpServletRequest request, @PathVariable int productId) throws Exception {
        int result = activityService.deleteActivityProduct(productId);
        return new HttpResponseBodyWrapper(result);
    }*/
	/**
	 * 删除活动与区域关联
	 * @param activityRegionId 活动与区域关联id
	 * @return HttpResponseBodyWrapper
	 * */
	@ResponseBody
	@DeleteMapping("/activity/delRgn/{activityRegionId}")
	public HttpResponseBodyWrapper deletePro(HttpServletRequest request, @PathVariable String activityRegionId) throws Exception {
		Integer result = activityService.delRgnByActivityRegionId(activityRegionId);
		return new HttpResponseBodyWrapper(result);
	}
	

	
	/**
	 * 编辑活动，根据活动id获取活动详情
	 * @param activityId 活动id
	 * @return HttpResponseBodyWrapper
	 * */
	@ResponseBody
    @GetMapping("/activity/{activityId}")
    public HttpResponseBodyWrapper getBrand(HttpServletRequest request, @PathVariable String activityId) throws Exception {
        Activity activity = activityService.getActivityById(activityId);
        return new HttpResponseBodyWrapper(activity);
    }
	/**
	 * 编辑活动，保存活动信息
	 * @param activity 活动实体
	 * @return HttpResponseBodyWrapper
	 * */
	@ResponseBody
    @PutMapping("/activity")
    public HttpResponseBodyWrapper update(HttpServletRequest request, @RequestBody Activity activity) throws Exception {
		UserSession userSession = getUserSession(request);
		
		activity.setuAdmin(userSession.getAccount());
        activity.setCompanyId(userSession.getCompanyId());
        activity.setName(StringUtils.trimToNull(activity.getName()));
        
        Activity activity_temp = activityService.getActivityById(String.valueOf(activity.getId()));
        if(activity_temp != null && !(activity_temp.getName().equals(activity.getName()))){
        	Boolean flag = activityService.isExistsActivity(String.valueOf(userSession.getCompanyId()), activity.getName());
        	if(flag){
        		throw new BizzException(BizzException.error_code_invalid_params, "已存在名称为【"+activity.getName()+"】的活动");
        	}
        }
        
        Boolean result = activityService.updateActivity(userSession.getCompanyId(),activity);
        
        
        return new HttpResponseBodyWrapper(result);
    }
	
	/**
	 * 编辑活动，保存活动规则
	 * @param activity 活动实体
	 * @return HttpResponseBodyWrapper
	 * */
	@ResponseBody
    @PutMapping("/activity/updateActivityAbstract")
    public HttpResponseBodyWrapper updateAbstract(HttpServletRequest request, @RequestBody Activity activity) throws Exception {
		UserSession userSession = getUserSession(request);
		activity.setuAdmin(userSession.getAccount());
        
        
		if(activity.getIntroduction().length() > 600){
			throw new BizzException(BizzException.error_code_invalid_params, "活动简介输入字符不能超过600");
		}
        Boolean result = activityService.updateActivityAbstract(activity);
        
        return new HttpResponseBodyWrapper(result);
    }
	/**
	 * 获取活动简介
	 * @param activityId 活动id
	 * @return ModelAndView
	 * */
	@GetMapping("/activity/getActivityAbstract")
    public ModelAndView getActivityAbstract(HttpServletRequest request, String activityId) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        Activity activity = activityService.getActivityById(activityId);
        model.put("activityId", activityId);
        model.put("activity", activity);
        return new ModelAndView("activity_abstract").addAllObjects(model);
	}
	
	/**
	 * 启用/停用活动
	 * @param type 活动操作类型1启用,2停用
	 * @param page 分页游标
	 * @param id 活动id
	 * @return HttpResponseBodyWrapper
	 * */
	@ResponseBody
	@PostMapping("/activity/using")
    public HttpResponseBodyWrapper usingActivity(HttpServletRequest request,String type,String id,Integer page) throws Exception {
		page = (page == null || page < 1) ? 1 : page;
		Pageable<ActivityPrize> listResult = activityService.queryActivityPrize(page,id);
		if(listResult.getResultTotal() <= 0){
			throw new BizzException(BizzException.error_code_invalid_params, "该活动没有中奖规则，不能启用!");
		}
        
        Boolean result = activityService.usingActivity(id, type);
        
        return new HttpResponseBodyWrapper(result);
    }
	/**
	 * 检查活动是否添加了中奖规则
	 * */
	/*@ResponseBody
	@PostMapping("/activity/checkHavePrizeList")
	public HttpResponseBodyWrapper checkHavePrizeList(HttpServletRequest request,String id,Integer page) throws Exception {
		page = (page == null || page < 1) ? 1 : page;
		Pageable<ActivityPrize> result = activityService.queryActivityPrize(page,id);
		Boolean i = false;
		if(result.getResultTotal() > 0){
			i = true;
		}
		return new HttpResponseBodyWrapper(i);
	}*/
	
	
	
	/**
	 * 获取中奖规则列表
	 * @param page 分页游标
	 * @param activityId 活动id
	 * @return ModelAndView
	 * */
	@GetMapping("/activity/getActivityPrizeList")
	public ModelAndView getActivityPrizeList(HttpServletRequest request, String activityId,Integer page) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		//UserSession userSession = getUserSession(request);
		
		page = (page == null || page < 1) ? 1 : page;
		Pageable<ActivityPrize> result = activityService.queryActivityPrize(page,activityId);
		Activity activity = activityService.getActivityById(activityId);
		
		model.put("activityPrizeList", result);
		model.put("activityId", activityId);//活动id
		model.put("actBaseNub", activity.getActBaseNub());//参奖基数，用于页面计算中奖比例，中奖比例=投放数量/参奖基数
		model.put("actTimeStart", activity.getActTimeStart());
		model.put("sta", activity.getSta());
		
		return new ModelAndView("activity_prize").addAllObjects(model);
	}
	
	/**
	 * 增加活动中奖规则
	 * @param aPrize 活动中奖规则实体信息
	 * @return HttpResponseBodyWrapper
	 * */
	@ResponseBody
    @PostMapping("/activity/addPrize")
    public HttpResponseBodyWrapper addActivityPrize(HttpServletRequest request, @RequestBody ActivityPrize aPrize) throws Exception {
        
        UserSession userSession = getUserSession(request);
        aPrize.setcAdmin(userSession.getAccount());
        
        //判断中奖比例是否大于100%,大于则不能提交
        Double totalOdds = activityService.getTotalOdds(String.valueOf(aPrize.getActivityId()));
        Double temp = aPrize.getOdds()+totalOdds;
        if(temp > 100.00){
        	throw new BizzException(BizzException.error_code_invalid_params, "中奖比例之和不能大于100%，请重新设置奖品投放数量！");
        }
        
        if(aPrize.getOdds() == null){
        	throw new BizzException(BizzException.error_code_invalid_params, "中奖比例为空，请修改投放数量");
        }else{
        	if(aPrize.getOdds().isNaN()){
            	throw new BizzException(BizzException.error_code_invalid_params, "中奖比例必须为数字，请修改投放数量");
            }
        }
        
        Boolean flag = activityService.isExistsActivityPrize(String.valueOf(aPrize.getActivityId()), aPrize.getGradeName());
        if(flag){
        	throw new BizzException(BizzException.error_code_invalid_params, "该活动奖品等级已存在!");
        }
        Boolean result = activityService.insertActivityPrize(aPrize);
        return new HttpResponseBodyWrapper(result);
    }
	/**
	 * 删除活动与中奖规则关联
	 * @param id 中奖规则id
	 * @return HttpResponseBodyWrapper
	 * */
	@ResponseBody
    @DeleteMapping("/activity/deleteActivityPrize/{id}")
    public HttpResponseBodyWrapper deleteActivityPrize(HttpServletRequest request, @PathVariable int id) throws Exception {
        Boolean result = activityService.deleteActivityPrize(id);
        return new HttpResponseBodyWrapper(result);
    }
}
